package com.yixun.controller;

import com.yixun.entity.AreaTree;
import com.yixun.entity.YxProNewVariety;
import com.yixun.entity.YxNewSurveyXqRecord;
import com.yixun.entity.YxUser;
import com.yixun.mapper.AreaTreeMapper;
import com.yixun.mapper.YxProNewVarietyMapper;
import com.yixun.service.RedisService;
import com.yixun.service.YxNewSurveyXqRecordService;
import com.yixun.util.ResponseModel;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 畜禽普查记录(YxNewSurveyXqRecord)表控制层
 *
 * @author lbx
 * @since 2021-06-22 11:42:20
 */
@Controller
@RequestMapping("yxNewSurveyXqRecord")
public class YxNewSurveyXqRecordController extends BaseController{

    /*上传文件时，将文件路径 储存在redis中 若取消了提交 或者最终没有提交 定时任务会在周期类 删除该文件 以节省空间*/
    @Value("${file.redis_key}")
    public   String FILES_TO_BE_DELETED;
    /**
     * 2021/6/27 20:11
     * @apiNote 新发现畜禽普查首页
     */
    @GetMapping("index")
    public String goIndex(){
        YxUser yxUser = this.getSessionUser();
        System.err.println(yxUser);
        return "yxSurveyXqRecord/newDiscovery/index";
    }
    /**
     * 2021/6/27 20:11
     * @apiNote 新发现畜禽普查 添加页面
     */
    @GetMapping("addPage")
    public String addPage(){
        YxUser yxUser = this.getSessionUser();
        System.err.println(yxUser);
        return "yxSurveyXqRecord/newDiscovery/addPage";
    }

    /**
     * 服务对象
     */
    @Resource
    private YxNewSurveyXqRecordService YxNewSurveyXqRecordService;

    @Resource
    private RedisService redisService;


    /**
     * 通过主键查询单条数据
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    @ResponseBody
    public YxNewSurveyXqRecord selectOne(Long id) {
        return this.YxNewSurveyXqRecordService.queryById(id);
    }

    /**
     * 通过主键查询单条数据
     * @param id 主键
     * @return 单条数据
     */
    @RequestMapping("getOne/{id}")
    @ResponseBody
    public YxNewSurveyXqRecord getOne(@PathVariable Long id) {
        return this.YxNewSurveyXqRecordService.queryById(id);
    }



    /**
     * 分页查询
     * @param map start_num 当前页 page_size 每页条数
     * @return yxProCultureds 数据集合 list
     */
    @PostMapping("getList")
    @ResponseBody
    public Map<String, Object> selectListByPage(@RequestBody HashMap<String,Integer> map){
        int count = this.YxNewSurveyXqRecordService.getCount();
        List<YxNewSurveyXqRecord> surveyCanRecords = YxNewSurveyXqRecordService.queryAllByLimit(map.get("start_num"), map.get("page_size"));
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("list",surveyCanRecords);
        hashMap.put("count",count);
        return ResponseModel.getModel("success", "200", hashMap);
    }
    /**
     * 2021/6/27 20:12
     * @param map 相关实体类字段
     * @return i 受影响条数
     * @apiNote 添加一条数据
     */
    @PostMapping("createOne")
    @ResponseBody
    public Map<String, Object> create(@RequestBody HashMap<String,Object> map){
        YxUser user = this.getSessionUser();
        /*判断用户是 乡镇还是 区县*/
        if (user.getUser_type()==1){
            map.put("status",0);
        }
        if (user.getUser_type()==2) {
            map.put("status",1);
        }
        String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        map.put("pcDay", date);
        map.put("addUser",user.getUser_id());
        map.put("userId",user.getUser_id());
        map.put("addTime", date);
        int i = YxNewSurveyXqRecordService.insert(map);
        if (i>0){
            String imgUrlsString = ((String) map.get("imgUrl"));
            System.err.println(imgUrlsString);
            if (imgUrlsString!=null){
                String[] imgUrls = imgUrlsString.split(",");
                for (String imgUrl : imgUrls) {
                    System.out.println(FILES_TO_BE_DELETED);
                    redisService.deleteValueOfKey(FILES_TO_BE_DELETED, imgUrl);
                }
            }
            return ResponseModel.getModel("success", "200", i);
        }
        return ResponseModel.getModel("fail", "500", i);
    }
    /**
     * 2021/6/27 20:14
     * @apiNote 更新 status字段 例如 审核通过 提交 等等
     */
    @PostMapping("updateStatus/{id}")
    @ResponseBody
    public Map<String, Object> updateStatus(@PathVariable Integer id){
        int i = YxNewSurveyXqRecordService.updateStatus(id);
        return ResponseModel.getModel("success", "200", i);
    }
    /**
     * 2021/6/27 20:15
     * @apiNote 退回 设置isGoBack字段为 -1
     */
    @PostMapping("goBack/{id}")
    @ResponseBody
    public Map<String, Object> goBack(@PathVariable Integer id){
        int i = YxNewSurveyXqRecordService.goBack(id);
        return ResponseModel.getModel("success", "200", i);
    }
    /**
     * 2021/6/27 20:15
     * @apiNote 设置饲养环境  该方法用于 table中的复选框 直接点击生效
     */
    @RequestMapping("setEnvironment")
    @ResponseBody
    public Integer setEnvironment(@RequestBody HashMap<String,Object> map){
        ArrayList<String> environmentList = (ArrayList<String>) map.get("environment");
        if (environmentList.size()>0) {
            StringBuffer stringBuffer =new StringBuffer();
            for (String s : environmentList) {
                stringBuffer.append(s).append(",");
            }
            StringBuffer environment = stringBuffer.deleteCharAt(stringBuffer.length() - 1);
            map.put("environment",environment.toString());
        }else {
            map.put("environment","");
        }
        System.err.println(map);
        return YxNewSurveyXqRecordService.updateEnvironment(map);
    }
    /*该接口用于生成 地区树*/
    @Resource
    private AreaTreeMapper areaTreeMapper;
    /**
     * @param code 行政编码
     * @return AreaTree 该行政区 下属辖地
     * @apiNote getVillages 获取地区数
     */
    @RequestMapping("getVillages/{code}")
    @ResponseBody
    public List<AreaTree> getVillages(@PathVariable String code){
        HashMap<String, Object> map = new HashMap<>();
        map.put("AreaCode",code);
        map.put("dqLevel",0);
        return areaTreeMapper.getOne(map);
    }
    /*新发现畜禽品种管理(YxProNewVariety)表数据库访问层*/
    @Resource
    private YxProNewVarietyMapper newVarietyMapper;
    /**
     * @apiNote 获取新品种
     * @author 吕兵星
     * @date 2021/6/27 20:21
     * @return java.util.List<java.util.HashMap < java.lang.String, java.lang.String>>
     */
    @RequestMapping("getVarieties")
    @ResponseBody
    public List<HashMap<String,String>> getVarieties(){
        List<YxProNewVariety> list = newVarietyMapper.queryAll(1);
        ArrayList<HashMap<String, String>> hashMaps = new ArrayList<>();
        for (YxProNewVariety variety : list) {
            HashMap<String, String> map = new HashMap<>();
            map.put("label",variety.getVarietyName());
            map.put("value", String.valueOf(variety.getNewVarietyId()));
            hashMaps.add(map);
        }
        return hashMaps;
    }
    /**
     * @apiNote 条件搜索
     * @author 吕兵星
     * @date 2021/6/27 20:21
     * @param map 条件 字段 封装
     * @return java.util.List<com.yixun.entity.YxNewSurveyXqRecord>
     */
    @RequestMapping("getSearchList")
    @ResponseBody
    public HashMap<String, Object> getSearchList(@RequestBody HashMap<String,Object> map){
        System.err.println(map);
        ArrayList<String> villageIds = null;
        ArrayList<String> varieties = null;
        ArrayList<String> status = null;
        Integer offset = null;
        Integer limit = null;
        try {
            villageIds = (ArrayList<String>) map.get("Village");
            varieties = (ArrayList<String>) map.get("Variety");
            status = (ArrayList<String>) map.get("Status");
            offset = (Integer) map.get("start_num");
            limit = (Integer) map.get("page_size");
        } catch (Exception e) {
            e.printStackTrace();
        }
        map.clear();
        if (villageIds.size()>0) {
            map.put("Village", villageIds.get(villageIds.size()-1));
        }
        if (varieties.size()>0) {
            map.put("Variety", varieties.get(varieties.size()-1));
        }
        if (status.size()>0) {
            map.put("Status", status.get(status.size()-1));
        }
        map.put("offset",offset);
        map.put("limit",limit);
        System.err.println(map);
        List<YxNewSurveyXqRecord> list = YxNewSurveyXqRecordService.queryAll(map);
        int total = YxNewSurveyXqRecordService.getSearchCount(map);
        map.put("items",list);
        map.put("total",total);
        return map;
    }
    /**
     * @param type 类型  1、更新数据 但不 更新 status 2、更新且提交  status 向上
     * @return java.lang.String
     * @apiNote updateOne 更新一条数据
     */
    @RequestMapping("update/{type}")
    @ResponseBody
    public  int updateOne(@PathVariable int type,@RequestBody HashMap<String,Object> map){
        int i=0;
        switch (type){
            case 1:{
                i = YxNewSurveyXqRecordService.updateOne(map);
                break;
            }
            case 2:{
                String status = (String) map.get("status");
                switch (status){
                    case "0":{
                        map.put("status",10);
                        break;
                    }
                    case "1":
                    case "10": {
                        map.put("status",20);
                        break;
                    }
                    case "20":{
                        map.put("status",30);
                        break;
                    }
                    case "30":{
                        map.put("status",31);
                        break;
                    }
                    case "31":{
                        break;
                    }
                }
                 i = YxNewSurveyXqRecordService.updateOne(map);
                break;
            }
        }
        String imgUrlsString = ((String) map.get("imgUrl"));
        if (imgUrlsString!=null){
            String[] imgUrls = imgUrlsString.split(",");
            for (String imgUrl : imgUrls) {
                redisService.deleteValueOfKey(FILES_TO_BE_DELETED, imgUrl);
            }
        }
        return i;
    }

    /**
     * @apiNote 到处数据到 excel
     * @author 吕兵星
     * @date 2021/6/27 20:22
     * @param response null
     * @return void
     */
    @RequestMapping(value = "/excel/export")
    public void exportExcel( HttpServletResponse response)
            throws Exception {
        HSSFWorkbook wb = YxNewSurveyXqRecordService.export();
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment;filename=livestockAndPoultryCensus.xls");
        OutputStream ouputStream = response.getOutputStream();
        wb.write(ouputStream);
        ouputStream.flush();
        ouputStream.close();
    }
}
